package com.rkc.handler;

import com.rkc.exception.BizException;
import com.rkc.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author `RKC`
 * @date 2021/10/10 14:20
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData exceptionHandler(Exception e) {
        log.error(e.getMessage());
        //判断是否是自定义异常
        if (e instanceof BizException) {
            BizException bizException = (BizException) e;
            log.error("[业务异常 {}]", e);
            return JsonData.buildCodeAndMsg(bizException.getCode(), bizException.getMsg());
        } else {
            log.error("[系统异常 {}]", e);
            return JsonData.buildError("全局异常，未知错误");
        }
    }
}
